﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;
using Newtonsoft.Json;

using CE.HotelEan;
using HotelWS;
using CE.Expedia;

public partial class travel_hotels_details : System.Web.UI.Page
{

    HotelServicesImplService hws = new HotelServicesImplService();

    private string _apikey = "98pndgasdzzxpugjzqpxw6za";
    private int _minorrev = 13;
    private Int64 _cid = 381988;

    private string _suppliertype = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        this.Page.Culture = "en-US";

        if (!Page.IsPostBack)
        {
            if (Request.QueryString["hid"] != null)
            {
                GetHotelDetails();

                if (Session["hotelsearchid"] != null)
                {
                    GetRoomAvailability();
                }
            }
        }
    }

    private void GetHotelDetails()
    {
        HotelInformationRequest hotelreq = new HotelInformationRequest();
        hotelreq.apiKey = _apikey;
        hotelreq.cid = _cid;
        hotelreq.minorRev = _minorrev;
        hotelreq.minorRevSpecified = true;
        hotelreq.customerIpAddress = Request.UserHostAddress;
        hotelreq.customerUserAgent = Request.Browser.ToString();
        hotelreq.customerSessionId = "";
        hotelreq.currencyCode = "SGD";
        hotelreq.locale = LocaleType.en_US;
        hotelreq.localeSpecified = true;
        hotelreq.hotelId = Convert.ToInt64(Request.QueryString["hid"].ToString());

        string getData = "http://api.ean.com/ean-services/rs/hotel/v3/info?cid=" + hotelreq.cid
                + "&minorRev=26&apiKey=" + hotelreq.apiKey
                + "&locale=" + hotelreq.locale
                + "&currencyCode=" + hotelreq.currencyCode
                + "&customerIpAddress=" + hotelreq.customerIpAddress
                + "&customerUserAgent=" + hotelreq.customerUserAgent
                + "&_type=xml&customerSessionId=" + hotelreq.customerSessionId
                + "&xml="
                + "<HotelInformationRequest><hotelId>" + hotelreq.hotelId +
                "</hotelId>";

        getData += "</HotelInformationRequest>";

        CXHotelInfo hotelresp = new CXHotelInfo();

        // Handle JsonConvert array bug
        string returnJson = "";
        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
        doc.LoadXml(getXMLResult(getData));
        foreach (System.Xml.XmlNode item in doc.SelectNodes("//Suppliers"))
        {
            item.AppendChild(doc.CreateNode("element", "Supplier", ""));
        }
        foreach (System.Xml.XmlNode item in doc.SelectNodes("//roomAmenities"))
        {
            item.AppendChild(doc.CreateNode("element", "RoomAmenity", ""));
        }
        foreach (System.Xml.XmlNode item in doc.SelectNodes("//RoomTypes"))
        {
            item.AppendChild(doc.CreateNode("element", "RoomType", ""));
        }
        returnJson = JsonConvert.SerializeXmlNode(doc).Replace(",null]", "]");

        returnJson = returnJson.Replace("@", "");
        returnJson = returnJson.Replace("\"xmlns:ns2\":\"http://v3.hotel.wsapi.ean.com/\",", "");
        returnJson = returnJson.Replace("ns2:", "");
        hotelresp = JsonConvert.DeserializeObject<CXHotelInfo>(returnJson);

        //HotelInformationResponse hotelresp = new HotelInformationResponse();
        //hotelresp = hws.getInformation(hotelreq);

        if (hotelresp.HotelInformationResponse.HotelSummary != null && hotelresp.HotelInformationResponse.EanWsError == null)
        {
            lblHotelName.Text = hotelresp.HotelInformationResponse.HotelSummary.name;
            lblAddress.Text = hotelresp.HotelInformationResponse.HotelSummary.address1 + " , " + hotelresp.HotelInformationResponse.HotelSummary.city + " , " + hotelresp.HotelInformationResponse.HotelSummary.countryCode
                + " , " + hotelresp.HotelInformationResponse.HotelSummary.postalCode;

            //lblCurrency.Text = "SGD"; // hotelresp.HotelSummary.rateCurrencyCode;
            //int avgprice = (int)(Math.Round((hotelresp.HotelSummary.lowRate + hotelresp.HotelSummary.highRate) / 2));

            //lblPrice.Text = avgprice.ToString();

            string _hotelrating = hotelresp.HotelInformationResponse.HotelSummary.hotelRating.ToString();

            if (_hotelrating == "0")
            { btnRatings.CssClass = "rating-0"; }
            else if (_hotelrating == "1")
            { btnRatings.CssClass = "rating-1"; }
            else if (_hotelrating == "1.5")
            { btnRatings.CssClass = "rating-15"; }
            else if (_hotelrating == "2")
            { btnRatings.CssClass = "rating-2"; }
            else if (_hotelrating == "2.5")
            { btnRatings.CssClass = "rating-25"; }
            else if (_hotelrating == "3")
            { btnRatings.CssClass = "rating-3"; }
            else if (_hotelrating == "3.5")
            { btnRatings.CssClass = "rating-35"; }
            else if (_hotelrating == "4")
            { btnRatings.CssClass = "rating-4"; }
            else if (_hotelrating == "4.5")
            { btnRatings.CssClass = "rating-45"; }
            else if (_hotelrating == "5")
            { btnRatings.CssClass = "rating-5"; }

            if (hotelresp.HotelInformationResponse.HotelDetails != null)
            {
                if (hotelresp.HotelInformationResponse.HotelDetails.drivingDirections != null)
                {
                    lblLocationDescription.InnerHtml = System.Web.HttpUtility.HtmlDecode(hotelresp.HotelInformationResponse.HotelDetails.drivingDirections);
                }

                if (hotelresp.HotelInformationResponse.HotelDetails.areaInformation != null)
                {
                    lblLocationDescription.InnerHtml += System.Web.HttpUtility.HtmlDecode(hotelresp.HotelInformationResponse.HotelDetails.areaInformation);
                }

                //lblDescription.InnerHtml = System.Web.HttpUtility.HtmlDecode(hotelresp.HotelDetails.propertyDescription);

                if (hotelresp.HotelInformationResponse.HotelDetails.checkInTime != "")
                {
                    divCheckinDates.Visible = false;
                    lblCheckin.Text = hotelresp.HotelInformationResponse.HotelDetails.checkInTime;
                    lblCheckout.Text = hotelresp.HotelInformationResponse.HotelDetails.checkOutTime;
                }

                if (hotelresp.HotelInformationResponse.HotelDetails.numberOfFloorsSpecified)
                {
                    lblNoOfFloors.Text = hotelresp.HotelInformationResponse.HotelDetails.numberOfFloors.ToString();
                }

                if (hotelresp.HotelInformationResponse.HotelDetails.numberOfRoomsSpecified)
                {
                    lblNoOfRooms.Text = hotelresp.HotelInformationResponse.HotelDetails.numberOfRooms.ToString();
                }

            }

            imgHotel.ImageUrl = "~/images/hotel/hotel_noimg.jpg";
            imgOverviewImage.ImageUrl = "~/images/hotel/hotel_noimg.jpg";

            if (hotelresp.HotelInformationResponse.HotelImages != null)
            {
                if (hotelresp.HotelInformationResponse.HotelImages.size > 0)
                {
                    if (hotelresp.HotelInformationResponse.HotelImages.HotelImage[0] != null)
                    {
                        if (hotelresp.HotelInformationResponse.HotelImages.HotelImage[0].url != null)
                        {
                            imgHotel.ImageUrl = hotelresp.HotelInformationResponse.HotelImages.HotelImage[0].url.ToString();
                            imgOverviewImage.ImageUrl = hotelresp.HotelInformationResponse.HotelImages.HotelImage[0].url.ToString();
                        }
                    }
                }
                else
                {
                    tabPhotos.Visible = false;
                }

            }

            if (hotelresp.HotelInformationResponse.HotelImages.size > 0)
            {
                foreach (CE.HotelEan.HotelImage hotelimg in hotelresp.HotelInformationResponse.HotelImages.HotelImage)
                {
                    HtmlGenericControl imglink = new HtmlGenericControl("a");
                    imglink.Attributes.Add("href", "#");
                    imglink.Attributes.Add("onmouseover", "ShowPicture('" + hotelimg.hotelImageId.ToString() + "',1)");
                    imglink.Attributes.Add("onmouseout", "ShowPicture('" + hotelimg.hotelImageId.ToString() + "',0)");

                    Image imgHotelthumb = new Image();

                    if (hotelimg.thumbnailUrl != null)
                    {
                        imgHotelthumb.ImageUrl = hotelimg.thumbnailUrl.ToString();
                        imgHotelthumb.ID = "imgthumb" + hotelimg.hotelImageId.ToString();
                    }

                    imglink.Controls.Add(imgHotelthumb);

                    HtmlGenericControl divPic = new HtmlGenericControl("div");
                    divPic.Attributes.Add("id", hotelimg.hotelImageId.ToString());
                    divPic.Attributes.Add("class", "picpreview");

                    HtmlGenericControl webimg = new HtmlGenericControl("img");

                    if (hotelimg.url != null)
                    {
                        webimg.Attributes.Add("src", hotelimg.url.ToString());
                        webimg.Attributes.Add("width", "370px");
                        webimg.Attributes.Add("height", "270px");
                    }

                    divPic.Controls.Add(webimg);

                    tdHotelPics.Controls.Add(imglink);
                    //tdHotelPics.Controls.Add(divPic);

                    tdHotelPicPreview.Controls.Add(divPic);

                }

            }

            if (hotelresp.HotelInformationResponse.PropertyAmenities != null)
            {
                lblAmenities.InnerHtml = "<b>Additional Amenities</b> <br/>";

                foreach (CE.HotelEan.PropertyAmenity propertyrow in hotelresp.HotelInformationResponse.PropertyAmenities.PropertyAmenity)
                {
                    //lblAmenities.InnerHtml += " <li> " + propertyrow.amenity.ToString() + "</li>";
                    lblAmenities.InnerHtml += propertyrow.amenity.ToString() + " * ";

                }

            }

            inputLat.Value = hotelresp.HotelInformationResponse.HotelSummary.latitude.ToString();
            inputLong.Value = hotelresp.HotelInformationResponse.HotelSummary.longitude.ToString();

        }
        else
        {
            lblMessage.Text = hotelresp.HotelInformationResponse.EanWsError.presentationMessage;
        }
    }

    private void GetRoomAvailability()
    {
        Int64 hotelsearchid = int.Parse(Session["hotelsearchid"].ToString());
        ExpediaHotelDB expdb = new ExpediaHotelDB();
        DataTable dtsearch = new DataTable();

        dtsearch = expdb.GetHotelSearchDetails(hotelsearchid);

        if (dtsearch.Rows.Count > 0)
        {
            string chkin = "";
            string chkout = "";
            string checkindate = "";
            string checkoutdate = "";

            if (dtsearch.Rows[0]["arrivalDate"].ToString() != "1/1/1900 12:00:00 AM")
            {
                chkin = Convert.ToDateTime(dtsearch.Rows[0]["arrivalDate"].ToString(), System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy");
                chkout = Convert.ToDateTime(dtsearch.Rows[0]["departureDate"].ToString(), System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy");
            }

            if (chkin != "")
            {
                string[] checkinformatted = chkin.Split('/');
                checkindate = checkinformatted[1] + "-" + checkinformatted[0] + "-" + checkinformatted[2];

                string[] checkoutformatted = chkout.Split('/');
                checkoutdate = checkoutformatted[1] + "-" + checkoutformatted[0] + "-" + checkoutformatted[2];

                HotelRoomAvailabilityRequest roomavail = new HotelRoomAvailabilityRequest();
                roomavail.apiKey = _apikey;
                roomavail.cid = _cid;
                roomavail.minorRev = _minorrev;
                roomavail.customerIpAddress = Request.UserHostAddress;
                roomavail.customerUserAgent = Request.Browser.ToString();
                roomavail.customerSessionId = "";
                roomavail.currencyCode = "SGD";
                roomavail.hotelId = int.Parse(Request.QueryString["hid"]);
                roomavail.arrivalDate = checkindate;
                roomavail.departureDate = checkoutdate;
                roomavail.locale = LocaleType.en_US;
                roomavail.includeDetails = true;
                roomavail.includeDetailsSpecified = true;
                roomavail.localeSpecified = true;
                roomavail.minorRevSpecified = true;

                DataTable dtRoom = new DataTable();
                ExpediaHotelRoomDB exproomdb = new ExpediaHotelRoomDB();

                dtRoom = exproomdb.GetRoomDetails(hotelsearchid);

                int guestAdult = 0;
                int guestChild = 0;

                string _strRoomXml = "";

                if (dtRoom.Rows.Count > 0)
                {
                    int iRoomCount = Convert.ToInt32(dtRoom.Rows.Count.ToString());
                    HotelWS.Room[] noofroom = new HotelWS.Room[iRoomCount];
                    for (int i = 0; i < iRoomCount; i++)
                    {
                        HotelWS.Room roomdtls = new HotelWS.Room();

                        roomdtls.numberOfAdults = int.Parse(dtRoom.Rows[i]["NoOfAdults"].ToString());
                        roomdtls.numberOfChildren = int.Parse(dtRoom.Rows[i]["NoOfChildren"].ToString());
                        roomdtls.numberOfChildrenSpecified = true;

                        noofroom[i] = roomdtls;

                        guestAdult = roomdtls.numberOfAdults + guestAdult;
                        guestChild = roomdtls.numberOfChildren + guestChild;

                        _strRoomXml += "<Room>" +
                            "<numberOfAdults>" + dtRoom.Rows[i]["NoOfAdults"].ToString() + "</numberOfAdults>";
                        if (roomdtls.numberOfChildren > 0)
                        {
                            _strRoomXml += "<numberOfChildren>" + dtRoom.Rows[i]["NoOfChildren"].ToString() + "</numberOfChildren>" +
                                    "<childAges>" + dtRoom.Rows[i]["info1"].ToString() + "</childAges>";
                        }
                        _strRoomXml += "</Room>";

                    }
                    roomavail.RoomGroup = noofroom;
                    roomavail.numberOfBedRooms = iRoomCount;
                    roomavail.numberOfBedRoomsSpecified = true;
                }

                lblSearchDetails.Text = "From: " + chkin + " To: " + chkout + "  Rooms: " + dtRoom.Rows.Count.ToString();
                lblSearchDetails.Text += " Guests: " + guestAdult.ToString() + " Adults ";

                if (guestChild > 0)
                {
                    lblSearchDetails.Text += guestChild.ToString() + " Child";
                }

                hotelAvailOption[] hotOptions = new hotelAvailOption[5];
                //hotelAvailOption roomtypes_opt = new hotelAvailOption();

                //roomtypes_opt = hotelAvailOption.ROOM_TYPES;
                //roomtypes_opt = hotelAvailOption.HOTEL_DETAILS;
                hotOptions[0] = hotelAvailOption.HOTEL_DETAILS;
                hotOptions[1] = hotelAvailOption.ROOM_TYPES;
                hotOptions[2] = hotelAvailOption.PROPERTY_AMENITIES;
                hotOptions[3] = hotelAvailOption.ROOM_AMENITIES;
                hotOptions[4] = hotelAvailOption.HOTEL_IMAGES;
                roomavail.options = hotOptions;

                //reformat date
                roomavail.arrivalDate = roomavail.arrivalDate.Replace("-", "/");
                roomavail.departureDate = roomavail.departureDate.Replace("-", "/");

                string getData = "http://api.ean.com/ean-services/rs/hotel/v3/avail?cid=" + roomavail.cid
                + "&minorRev=26&apiKey=" + roomavail.apiKey
                + "&locale=" + roomavail.locale
                + "&currencyCode=" + roomavail.currencyCode
                + "&customerIpAddress=" + roomavail.customerIpAddress
                + "&customerUserAgent=" + roomavail.customerUserAgent
                + "&_type=xml&customerSessionId=" + roomavail.customerSessionId
                + "&xml="
                + "<HotelRoomAvailabilityRequest><hotelId>" + roomavail.hotelId +
                "</hotelId><arrivalDate>" + roomavail.arrivalDate +
                "</arrivalDate><departureDate>" + roomavail.departureDate +
                "</departureDate><includeDetails>" + roomavail.includeDetails +
                "</includeDetails><numberOfBedRooms>" + roomavail.numberOfBedRooms +
                "</numberOfBedRooms><RoomGroup>" + _strRoomXml +
                "</RoomGroup><options>" + "HOTEL_DETAILS,ROOM_TYPES,PROPERTY_AMENITIES,ROOM_AMENITIES,HOTEL_IMAGES" +
                "</options>";

                getData += "</HotelRoomAvailabilityRequest>";

                CXHotelRoomAvail roomresponse = new CXHotelRoomAvail();

                // Handle JsonConvert array bug
                string returnJson = "";
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.LoadXml(getXMLResult(getData));
                foreach (System.Xml.XmlNode item in doc.SelectNodes("//RateInfos"))
                {
                    item.AppendChild(doc.CreateNode("element", "RateInfo", ""));
                }
                foreach (System.Xml.XmlNode item in doc.SelectNodes("//Surcharges"))
                {
                    item.AppendChild(doc.CreateNode("element", "Surcharge", ""));
                }
                foreach (System.Xml.XmlNode item in doc.SelectNodes("//CancelPolicyInfoList"))
                {
                    item.AppendChild(doc.CreateNode("element", "CancelPolicyInfo", ""));
                }
                foreach (System.Xml.XmlNode item in doc.SelectNodes("//ValueAdds"))
                {
                    item.AppendChild(doc.CreateNode("element", "ValueAdd", ""));
                }
                foreach (System.Xml.XmlNode item in doc.SelectNodes("//Suppliers"))
                {
                    item.AppendChild(doc.CreateNode("element", "Supplier", ""));
                }
                foreach (System.Xml.XmlNode item in doc.SelectNodes("//BedTypes"))
                {
                    item.AppendChild(doc.CreateNode("element", "BedType", ""));
                }
                foreach (System.Xml.XmlNode item in doc.SelectNodes("//roomAmenities"))
                {
                    item.AppendChild(doc.CreateNode("element", "RoomAmenity", ""));
                }
                foreach (System.Xml.XmlNode item in doc.SelectNodes("//HotelFees"))
                {
                    item.AppendChild(doc.CreateNode("element", "HotelFee", ""));
                }
                foreach (System.Xml.XmlNode item in doc.SelectNodes("//RoomTypes"))
                {
                    item.AppendChild(doc.CreateNode("element", "RoomType", ""));
                }
                System.Xml.XmlElement root = doc.DocumentElement;
                root.AppendChild(doc.CreateNode("element", "HotelRoomResponse", ""));
                returnJson = JsonConvert.SerializeXmlNode(doc).Replace(",null]", "]");

                returnJson = returnJson.Replace("@", "");
                returnJson = returnJson.Replace("\"xmlns:ns2\":\"http://v3.hotel.wsapi.ean.com/\",", "");
                returnJson = returnJson.Replace("ns2:", "");
                roomresponse = JsonConvert.DeserializeObject<CXHotelRoomAvail>(returnJson);

                //HotelRoomAvailabilityResponse roomresponse = new HotelRoomAvailabilityResponse();
                //roomresponse = hws.getAvailability(roomavail);


                if (roomresponse != null && roomresponse.HotelRoomAvailabilityResponse.EanWsError == null)
                {

                    string propertydesc = ""; // roomresponse.HotelDetails.propertyDescription;

                    int notifindex = 0;

                    if (roomresponse.HotelRoomAvailabilityResponse.HotelDetails.propertyDescription != null)
                    {
                        propertydesc = roomresponse.HotelRoomAvailabilityResponse.HotelDetails.propertyDescription;
                        notifindex = roomresponse.HotelRoomAvailabilityResponse.HotelDetails.propertyDescription.IndexOf("&lt;p&gt;&lt;strong&gt;Notifications");
                    }

                    if (notifindex > 0)
                    {
                        propertydesc = roomresponse.HotelRoomAvailabilityResponse.HotelDetails.propertyDescription.Remove(notifindex, propertydesc.Length - notifindex);
                    }

                    lblPropertyDesc.InnerHtml = System.Web.HttpUtility.HtmlDecode(propertydesc).Replace("<br /><br />", "");

                    if (roomresponse.HotelRoomAvailabilityResponse.HotelDetails.roomInformation != null)
                    {
                        string notif = System.Web.HttpUtility.HtmlDecode(roomresponse.HotelRoomAvailabilityResponse.HotelDetails.roomInformation);
                        if (notif.IndexOf("<br /><br />", 0) == 0)
                        {
                            notif = notif.Remove(0, 12);
                        }

                        lblNotification.InnerHtml = notif.Replace("<p>", "").Replace("</p>", "");

                    }

                    if (roomresponse.HotelRoomAvailabilityResponse.HotelDetails.hotelPolicy != null)
                    {
                        lblPolicy.InnerHtml = "<br/>" + roomresponse.HotelRoomAvailabilityResponse.HotelDetails.hotelPolicy.Replace(".", ". <br/>") + "<br/>";
                    }

                    if (roomresponse.HotelRoomAvailabilityResponse.HotelDetails.checkInInstructions != null)
                    {
                        lblPolicy.InnerHtml += System.Web.HttpUtility.HtmlDecode(roomresponse.HotelRoomAvailabilityResponse.HotelDetails.checkInInstructions);
                    }

                    if (roomresponse.HotelRoomAvailabilityResponse.HotelDetails.propertyInformation != null)
                    {
                        lblPolicy.InnerHtml += System.Web.HttpUtility.HtmlDecode(roomresponse.HotelRoomAvailabilityResponse.HotelDetails.propertyInformation) + "<br/>";
                    }

                    Session["customerSessionId"] = roomresponse.HotelRoomAvailabilityResponse.customerSessionId;
                    BindRooms(roomresponse.HotelRoomAvailabilityResponse);

                    if (roomresponse.HotelRoomAvailabilityResponse.HotelRoomResponse != null)
                    {
                        _suppliertype = roomresponse.HotelRoomAvailabilityResponse.HotelRoomResponse[0].supplierType.ToString();

                        if (_suppliertype != "E")
                        {
                            lblAgencyDisclaimer.Text = "*You are booking a non-discounted property. All rates displayed are nightly, and based on double occupancy per room unless otherwise specified. Carefully review the room descriptions and rate rules to ensure the room you select can accommodate your entire party. Some rates may require special identification. Our booking  fee, taxes, and other surcharges imposed by the hotel are not included. Any extra adults or children above the room's listed occupancy may be subject to additional  charges at the property's discretion.";

                            if (_suppliertype == "W")
                            {
                                imgWorldspan.Visible = true;
                            }
                        }
                        else
                        {
                            lblAgencyDisclaimer.Text = "*The room rates listed are for double occupancy per room unless otherwise stated and exclude tax recovery charges and service fees.";
                        }

                        if (roomresponse.HotelRoomAvailabilityResponse.HotelRoomResponse[0].RateInfos.RateInfo[0].ChargeableRateInfo.currencyCode == "SGD")
                        {
                            lblCurrency.Text = roomresponse.HotelRoomAvailabilityResponse.HotelRoomResponse[0].RateInfos.RateInfo[0].ChargeableRateInfo.currencyCode;
                            lblPrice.Text = Math.Round(roomresponse.HotelRoomAvailabilityResponse.HotelRoomResponse[0].RateInfos.RateInfo[0].ChargeableRateInfo.averageBaseRate).ToString();

                            if (_suppliertype != "E")
                            {
                                lblratedesc.Text = "single night rate per room excl. taxes and fees";
                                lblPrice.Text = Math.Round(roomresponse.HotelRoomAvailabilityResponse.HotelRoomResponse[0].RateInfos.RateInfo[0].ChargeableRateInfo.maxNightlyRate).ToString();

                                lblDisclaimerRates.Text = "Taxes and Other Surcharges Imposed by the Hotel are Not Included.";
                            }

                            if (roomresponse.HotelRoomAvailabilityResponse.HotelRoomResponse[0].RateInfos.RateInfo[0].promo)
                            {
                                lblCurrency.Text = "<s>" + lblCurrency.Text + "</s>";
                                lblPrice.Text = "<s>" + lblPrice.Text + "</s>";
                                lblCurrency2.Text = roomresponse.HotelRoomAvailabilityResponse.HotelRoomResponse[0].RateInfos.RateInfo[0].ChargeableRateInfo.currencyCode;
                                lblPromoPrice.Text = Math.Round(roomresponse.HotelRoomAvailabilityResponse.HotelRoomResponse[0].RateInfos.RateInfo[0].ChargeableRateInfo.averageRate).ToString();
                            }
                        }
                        else
                        {
                            lblCurrency.Text = roomresponse.HotelRoomAvailabilityResponse.HotelRoomResponse[0].RateInfos.RateInfo[0].ConvertedRateInfo.currencyCode;
                            lblPrice.Text = Math.Round(roomresponse.HotelRoomAvailabilityResponse.HotelRoomResponse[0].RateInfos.RateInfo[0].ConvertedRateInfo.averageBaseRate).ToString();

                            if (_suppliertype != "E")
                            {
                                lblratedesc.Text = "nightly rate per room excl. taxes and fees";
                                lblPrice.Text = Math.Round(roomresponse.HotelRoomAvailabilityResponse.HotelRoomResponse[0].RateInfos.RateInfo[0].ConvertedRateInfo.maxNightlyRate).ToString();

                                lblDisclaimerRates.Text = "Taxes and Other Surcharges Imposed by the Hotel are Not Included.";
                            }

                            if (roomresponse.HotelRoomAvailabilityResponse.HotelRoomResponse[0].RateInfos.RateInfo[0].promo)
                            {
                                lblCurrency.Text = "<s>" + lblCurrency.Text + "</s>";
                                lblPrice.Text = "<s>" + lblPrice.Text + "</s>";
                                lblCurrency2.Text = roomresponse.HotelRoomAvailabilityResponse.HotelRoomResponse[0].RateInfos.RateInfo[0].ConvertedRateInfo.currencyCode;
                                lblPromoPrice.Text = Math.Round(roomresponse.HotelRoomAvailabilityResponse.HotelRoomResponse[0].RateInfos.RateInfo[0].ConvertedRateInfo.averageRate).ToString();
                            }
                        }
                    }
                }
                else
                {
                    gvRooms.EmptyDataText = roomresponse.HotelRoomAvailabilityResponse.EanWsError.presentationMessage;
                    gvRooms.DataBind();
                }


            }
        }
    }

    private CE.HotelEan.HotelRateRulesResponse GetRateRules(string customerSessionId, string ratecode, string roomtypecode, HotelWS.SupplierType suppliertype, string checkindate, string checkoutdate)
    {
        Int64 hotelsearchid = int.Parse(Session["hotelsearchid"].ToString());

        HotelRateRulesRequest roomreq = new HotelRateRulesRequest();
        roomreq.apiKey = _apikey;
        roomreq.cid = _cid;
        roomreq.minorRev = _minorrev;
        roomreq.customerIpAddress = Request.UserHostAddress;
        roomreq.customerUserAgent = Request.Browser.ToString();
        roomreq.customerSessionId = customerSessionId;
        roomreq.currencyCode = "SGD";
        roomreq.locale = LocaleType.en_US;
        roomreq.hotelId = int.Parse(Request.QueryString["hid"]);
        roomreq.arrivalDate = checkindate.Replace("-", "/");
        roomreq.departureDate = checkoutdate.Replace("-", "/");
        roomreq.supplierType = suppliertype;
        roomreq.rateCode = ratecode;
        roomreq.roomTypeCode = roomtypecode;

        DataTable dtRoom = new DataTable();
        ExpediaHotelRoomDB exproomdb = new ExpediaHotelRoomDB();

        dtRoom = exproomdb.GetRoomDetails(hotelsearchid);

        string _strRoomXml = "";

        if (dtRoom.Rows.Count > 0)
        {
            int iRoomCount = Convert.ToInt32(dtRoom.Rows.Count.ToString());
            HotelWS.Room[] noofroom = new HotelWS.Room[iRoomCount];
            for (int i = 0; i < iRoomCount; i++)
            {
                HotelWS.Room roomdtls = new HotelWS.Room();

                roomdtls.numberOfAdults = int.Parse(dtRoom.Rows[i]["NoOfAdults"].ToString());
                //roomdtls.numberOfChildren = int.Parse(dtRoom.Rows[i]["NoOfChildren"].ToString());
                //roomdtls.childAges
                //roomdtls.numberOfChildrenSpecified = true;

                noofroom[i] = roomdtls;

                _strRoomXml += "<Room>" +
                            "<numberOfAdults>" + dtRoom.Rows[i]["NoOfAdults"].ToString() + "</numberOfAdults>";
                if (roomdtls.numberOfChildren > 0)
                {
                    _strRoomXml += "<numberOfChildren>" + dtRoom.Rows[i]["NoOfChildren"].ToString() + "</numberOfChildren>" +
                            "<childAges>" + dtRoom.Rows[i]["info1"].ToString() + "</childAges>";
                }
                _strRoomXml += "</Room>";
            }
            roomreq.RoomGroup = noofroom;
        }

        string getData = "http://api.ean.com/ean-services/rs/hotel/v3/rules?cid=" + roomreq.cid
                + "&minorRev=26&apiKey=" + roomreq.apiKey
                + "&locale=" + roomreq.locale
                + "&currencyCode=" + roomreq.currencyCode
                + "&customerIpAddress=" + roomreq.customerIpAddress
                + "&customerUserAgent=" + roomreq.customerUserAgent
                + "&_type=xml&customerSessionId=" + roomreq.customerSessionId
                + "&xml="
                + "<HotelRateRulesRequest><hotelId>" + roomreq.hotelId +
                "</hotelId><arrivalDate>" + roomreq.arrivalDate +
                "</arrivalDate><departureDate>" + roomreq.departureDate +
                "</departureDate><supplierType>" + roomreq.supplierType.ToString() +
                "</supplierType><roomTypeCode>" + roomreq.roomTypeCode +
                "</roomTypeCode><rateCode>" + roomreq.rateCode +
                "</rateCode><RoomGroup>" + _strRoomXml +
                "</RoomGroup>";

        getData += "</HotelRateRulesRequest>";

        CXHotelRateRules roomresp = new CXHotelRateRules();

        // Handle JsonConvert array bug
        string returnJson = "";
        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
        doc.LoadXml(getXMLResult(getData));
        foreach (System.Xml.XmlNode item in doc.SelectNodes("//RateInfos"))
        {
            item.AppendChild(doc.CreateNode("element", "RateInfo", ""));
        }
        foreach (System.Xml.XmlNode item in doc.SelectNodes("//Surcharges"))
        {
            item.AppendChild(doc.CreateNode("element", "Surcharge", ""));
        }
        foreach (System.Xml.XmlNode item in doc.SelectNodes("//CancelPolicyInfoList"))
        {
            item.AppendChild(doc.CreateNode("element", "CancelPolicyInfo", ""));
        }
        foreach (System.Xml.XmlNode item in doc.SelectNodes("//ValueAdds"))
        {
            item.AppendChild(doc.CreateNode("element", "ValueAdd", ""));
        }
        foreach (System.Xml.XmlNode item in doc.SelectNodes("//Suppliers"))
        {
            item.AppendChild(doc.CreateNode("element", "Supplier", ""));
        }
        returnJson = JsonConvert.SerializeXmlNode(doc).Replace(",null]", "]");

        returnJson = returnJson.Replace("@", "");
        returnJson = returnJson.Replace("\"xmlns:ns2\":\"http://v3.hotel.wsapi.ean.com/\",", "");
        returnJson = returnJson.Replace("ns2:", "");
        roomresp = JsonConvert.DeserializeObject<CXHotelRateRules>(returnJson);

        //HotelRateRulesResponse roomresp = new HotelRateRulesResponse();
        //roomresp = hws.getRateRules(roomreq);

        return roomresp.HotelRateRulesResponse;
    }

    private void BindRooms(CE.HotelEan.HotelRoomAvailabilityResponse roomresponse)
    {

        DataTable dtRoomTbl = new DataTable();

        DataColumn col1 = new DataColumn("customerSessionId");
        DataColumn col2 = new DataColumn("hotelId");
        DataColumn col3 = new DataColumn("arrivalDate");
        DataColumn col4 = new DataColumn("departureDate");
        DataColumn col5 = new DataColumn("hotelName");
        DataColumn col6 = new DataColumn("hotelAddress");
        DataColumn col7 = new DataColumn("hotelCity");
        DataColumn col8 = new DataColumn("hotelStateProvince");
        DataColumn col9 = new DataColumn("hotelCountry");
        DataColumn col10 = new DataColumn("numberOfRoomsRequested");
        DataColumn col11 = new DataColumn("checkInInstructions");
        DataColumn col12 = new DataColumn("rateKey");

        //hotelroomresponse
        DataColumn col13 = new DataColumn("rateCode");
        DataColumn col14 = new DataColumn("roomTypeCode");
        DataColumn col15 = new DataColumn("roomTypeDescription");
        DataColumn col16 = new DataColumn("supplierType");
        DataColumn col17 = new DataColumn("taxRate");
        DataColumn col18 = new DataColumn("rateChange");
        DataColumn col19 = new DataColumn("nonRefundable");
        DataColumn col20 = new DataColumn("guaranteeRequired");
        DataColumn col21 = new DataColumn("depositRequired");
        DataColumn col22 = new DataColumn("immediateChargeRequired");
        DataColumn col23 = new DataColumn("currentAllotment");
        DataColumn col24 = new DataColumn("propertyId");
        DataColumn col25 = new DataColumn("rateOccupancyPerRoom");
        DataColumn col26 = new DataColumn("quotedOccupancy");
        DataColumn col27 = new DataColumn("minGuestAge");

        DataColumn col28 = new DataColumn("rateInfoRateChange");
        DataColumn col29 = new DataColumn("promo");
        DataColumn col30 = new DataColumn("priceBreakdown");
        DataColumn col31 = new DataColumn("numberOfAdults");
        DataColumn col32 = new DataColumn("numberOfChildren");
        DataColumn col33 = new DataColumn("commissionableUsdTotal");
        DataColumn col34 = new DataColumn("total");
        DataColumn col35 = new DataColumn("surchargeTotal");
        DataColumn col36 = new DataColumn("nightlyRateTotal");
        DataColumn col37 = new DataColumn("averageBaseRate");
        DataColumn col38 = new DataColumn("averageRate");
        DataColumn col39 = new DataColumn("maxNightlyRate");
        DataColumn col40 = new DataColumn("currencyCode");
        DataColumn col41 = new DataColumn("nightlyRatePromo");
        DataColumn col42 = new DataColumn("nightlyRate");
        DataColumn col43 = new DataColumn("baseRate");

        DataColumn col44 = new DataColumn("surchargeAmount");
        DataColumn col45 = new DataColumn("surchargeType");
        DataColumn col46 = new DataColumn("valueAdds");
        DataColumn col47 = new DataColumn("deepLink");

        //raterules
        DataColumn col48 = new DataColumn("roomTypeDescriptionLong");
        DataColumn col49 = new DataColumn("rooomTypeAmenities");
        DataColumn col50 = new DataColumn("cancellationPolicy");

        DataColumn col51 = new DataColumn("rateRules-ratePlanText");
        DataColumn col52 = new DataColumn("rateRules-nativeCurrencyCode");
        DataColumn col53 = new DataColumn("rateRules-guaranteeMethods");
        DataColumn col54 = new DataColumn("rateRules-cancellationPolicy");
        DataColumn col55 = new DataColumn("rateRules-miscellaneous");
        DataColumn col56 = new DataColumn("rateRules-extraChargeRollawayAdult");
        DataColumn col57 = new DataColumn("rateRules-extraChargeCrib");
        DataColumn col58 = new DataColumn("rateRules-extraChargeAdult");
        DataColumn col59 = new DataColumn("rateRules-roomDescription");
        DataColumn col60 = new DataColumn("rateRules-roomRate");
        DataColumn col61 = new DataColumn("rateRules-totalRoomRate");

        DataColumn col62 = new DataColumn("promoDescription");
        DataColumn col63 = new DataColumn("ArrayNightlyBaseRate");
        DataColumn col64 = new DataColumn("ArrayNightlyRate");
        DataColumn col65 = new DataColumn("ArraySurchargeType");
        DataColumn col66 = new DataColumn("ArraySurchargeAmount");
        DataColumn col67 = new DataColumn("ArrayPromo");

        dtRoomTbl.Columns.Add(col1);
        dtRoomTbl.Columns.Add(col2);
        dtRoomTbl.Columns.Add(col3);
        dtRoomTbl.Columns.Add(col4);
        dtRoomTbl.Columns.Add(col5);
        dtRoomTbl.Columns.Add(col6);
        dtRoomTbl.Columns.Add(col7);
        dtRoomTbl.Columns.Add(col8);
        dtRoomTbl.Columns.Add(col9);
        dtRoomTbl.Columns.Add(col10);
        dtRoomTbl.Columns.Add(col11);
        dtRoomTbl.Columns.Add(col12);

        dtRoomTbl.Columns.Add(col13);
        dtRoomTbl.Columns.Add(col14);
        dtRoomTbl.Columns.Add(col15);
        dtRoomTbl.Columns.Add(col16);
        dtRoomTbl.Columns.Add(col17);
        dtRoomTbl.Columns.Add(col18);
        dtRoomTbl.Columns.Add(col19);
        dtRoomTbl.Columns.Add(col20);
        dtRoomTbl.Columns.Add(col21);
        dtRoomTbl.Columns.Add(col22);
        dtRoomTbl.Columns.Add(col23);
        dtRoomTbl.Columns.Add(col24);
        dtRoomTbl.Columns.Add(col25);
        dtRoomTbl.Columns.Add(col26);
        dtRoomTbl.Columns.Add(col27);
        dtRoomTbl.Columns.Add(col28);
        dtRoomTbl.Columns.Add(col29);
        dtRoomTbl.Columns.Add(col30);
        dtRoomTbl.Columns.Add(col31);
        dtRoomTbl.Columns.Add(col32);
        dtRoomTbl.Columns.Add(col33);
        dtRoomTbl.Columns.Add(col34);
        dtRoomTbl.Columns.Add(col35);
        dtRoomTbl.Columns.Add(col36);
        dtRoomTbl.Columns.Add(col37);
        dtRoomTbl.Columns.Add(col38);
        dtRoomTbl.Columns.Add(col39);
        dtRoomTbl.Columns.Add(col40);
        dtRoomTbl.Columns.Add(col41);
        dtRoomTbl.Columns.Add(col42);
        dtRoomTbl.Columns.Add(col43);
        dtRoomTbl.Columns.Add(col44);

        dtRoomTbl.Columns.Add(col45);
        dtRoomTbl.Columns.Add(col46);
        dtRoomTbl.Columns.Add(col47);
        dtRoomTbl.Columns.Add(col48);

        dtRoomTbl.Columns.Add(col49);
        dtRoomTbl.Columns.Add(col50);
        dtRoomTbl.Columns.Add(col51);
        dtRoomTbl.Columns.Add(col52);
        dtRoomTbl.Columns.Add(col53);
        dtRoomTbl.Columns.Add(col54);
        dtRoomTbl.Columns.Add(col55);
        dtRoomTbl.Columns.Add(col56);
        dtRoomTbl.Columns.Add(col57);
        dtRoomTbl.Columns.Add(col58);

        dtRoomTbl.Columns.Add(col59);
        dtRoomTbl.Columns.Add(col60);
        dtRoomTbl.Columns.Add(col61);
        dtRoomTbl.Columns.Add(col62);
        dtRoomTbl.Columns.Add(col63);
        dtRoomTbl.Columns.Add(col64);
        dtRoomTbl.Columns.Add(col65);
        dtRoomTbl.Columns.Add(col66);
        dtRoomTbl.Columns.Add(col67);

        foreach (CE.HotelEan.HotelRoomResponse hotelroomrow in roomresponse.HotelRoomResponse)
        {
            DataRow row = dtRoomTbl.NewRow();

            row["customerSessionId"] = roomresponse.customerSessionId;
            row["hotelId"] = roomresponse.hotelId;
            row["arrivalDate"] = roomresponse.arrivalDate;
            row["departureDate"] = roomresponse.departureDate;
            row["hotelName"] = roomresponse.hotelName;
            row["hotelAddress"] = roomresponse.hotelAddress;
            row["hotelCity"] = roomresponse.hotelCity;
            row["hotelStateProvince"] = roomresponse.hotelStateProvince;
            row["hotelCountry"] = roomresponse.hotelCountry;
            row["numberOfRoomsRequested"] = roomresponse.numberOfRoomsRequested;
            row["checkInInstructions"] = roomresponse.checkInInstructions;
            row["rateKey"] = roomresponse.rateKey;

            row["rateCode"] = hotelroomrow.rateCode;
            //row["roomTypeCode"] = hotelroomrow.roomTypeCode;
            //row["roomTypeDescription"] = hotelroomrow.roomTypeDescription;
            row["supplierType"] = hotelroomrow.supplierType;
            row["taxRate"] = hotelroomrow.taxRate;
            row["rateChange"] = hotelroomrow.rateChange;
            row["nonRefundable"] = hotelroomrow.nonRefundable;
            row["guaranteeRequired"] = hotelroomrow.guaranteeRequired;
            row["depositRequired"] = hotelroomrow.depositRequired;

            row["immediateChargeRequired"] = hotelroomrow.immediateChargeRequired;
            row["currentAllotment"] = hotelroomrow.currentAllotment;
            row["propertyId"] = hotelroomrow.propertyId;

            row["rateOccupancyPerRoom"] = hotelroomrow.rateOccupancyPerRoom;
            row["quotedOccupancy"] = hotelroomrow.quotedOccupancy;
            row["minGuestAge"] = hotelroomrow.minGuestAge;

            if (hotelroomrow.RateInfos != null)
            {
                row["rateInfoRateChange"] = hotelroomrow.RateInfos.RateInfo[0].rateChange; // hotelroomrow.RateInfo.rateChange;
                row["promo"] = hotelroomrow.RateInfos.RateInfo[0].promo;
                row["priceBreakdown"] = hotelroomrow.RateInfos.RateInfo[0].priceBreakdown;

                if (hotelroomrow.RateInfos.RateInfo[0].RoomGroup != null)
                {
                    row["numberOfAdults"] = hotelroomrow.RateInfos.RateInfo[0].RoomGroup.numberOfAdults;
                    row["numberOfChildren"] = hotelroomrow.RateInfos.RateInfo[0].RoomGroup.numberOfChildren;
                }


                if (hotelroomrow.RateInfos.RateInfo[0].ChargeableRateInfo.currencyCode == "SGD")
                {
                    row["currencyCode"] = hotelroomrow.RateInfos.RateInfo[0].ChargeableRateInfo.currencyCode;
                    row["commissionableUsdTotal"] = hotelroomrow.RateInfos.RateInfo[0].ChargeableRateInfo.commissionableUsdTotal;
                    row["total"] = hotelroomrow.RateInfos.RateInfo[0].ChargeableRateInfo.total;
                    row["surchargeTotal"] = hotelroomrow.RateInfos.RateInfo[0].ChargeableRateInfo.surchargeTotal;
                    row["nightlyRateTotal"] = hotelroomrow.RateInfos.RateInfo[0].ChargeableRateInfo.nightlyRateTotal;
                    row["averageBaseRate"] = hotelroomrow.RateInfos.RateInfo[0].ChargeableRateInfo.averageBaseRate;
                    row["averageRate"] = hotelroomrow.RateInfos.RateInfo[0].ChargeableRateInfo.averageRate;
                    row["maxNightlyRate"] = hotelroomrow.RateInfos.RateInfo[0].ChargeableRateInfo.maxNightlyRate;

                    if (hotelroomrow.RateInfos.RateInfo[0].ChargeableRateInfo.NightlyRatesPerRoom != null)
                    {
                        row["nightlyRatePromo"] = hotelroomrow.RateInfos.RateInfo[0].ChargeableRateInfo.NightlyRatesPerRoom.NightlyRate[0].promo;
                        row["nightlyRate"] = hotelroomrow.RateInfos.RateInfo[0].ChargeableRateInfo.NightlyRatesPerRoom.NightlyRate[0].rate;
                        row["baseRate"] = hotelroomrow.RateInfos.RateInfo[0].ChargeableRateInfo.NightlyRatesPerRoom.NightlyRate[0].baseRate;

                        if (hotelroomrow.RateInfos.RateInfo[0].ChargeableRateInfo.Surcharges != null)
                        {
                            row["surchargeAmount"] = hotelroomrow.RateInfos.RateInfo[0].ChargeableRateInfo.Surcharges.Surcharge[0].amount;
                            row["surchargeType"] = hotelroomrow.RateInfos.RateInfo[0].ChargeableRateInfo.Surcharges.Surcharge[0].type;
                        }
                    }
                }
                else
                {
                    if (hotelroomrow.RateInfos.RateInfo[0].ConvertedRateInfo != null)
                    {
                        row["currencyCode"] = hotelroomrow.RateInfos.RateInfo[0].ConvertedRateInfo.currencyCode;
                        row["commissionableUsdTotal"] = hotelroomrow.RateInfos.RateInfo[0].ConvertedRateInfo.commissionableUsdTotal;
                        row["total"] = hotelroomrow.RateInfos.RateInfo[0].ConvertedRateInfo.total;
                        row["surchargeTotal"] = hotelroomrow.RateInfos.RateInfo[0].ConvertedRateInfo.surchargeTotal;
                        row["nightlyRateTotal"] = hotelroomrow.RateInfos.RateInfo[0].ConvertedRateInfo.nightlyRateTotal;
                        row["averageBaseRate"] = hotelroomrow.RateInfos.RateInfo[0].ConvertedRateInfo.averageBaseRate;
                        row["averageRate"] = hotelroomrow.RateInfos.RateInfo[0].ConvertedRateInfo.averageRate;
                        row["maxNightlyRate"] = hotelroomrow.RateInfos.RateInfo[0].ConvertedRateInfo.maxNightlyRate;

                        if (hotelroomrow.RateInfos.RateInfo[0].ConvertedRateInfo.NightlyRatesPerRoom != null)
                        {
                            row["nightlyRatePromo"] = hotelroomrow.RateInfos.RateInfo[0].ConvertedRateInfo.NightlyRatesPerRoom.NightlyRate[0].promo;
                            row["nightlyRate"] = hotelroomrow.RateInfos.RateInfo[0].ConvertedRateInfo.NightlyRatesPerRoom.NightlyRate[0].rate;
                            row["baseRate"] = hotelroomrow.RateInfos.RateInfo[0].ConvertedRateInfo.NightlyRatesPerRoom.NightlyRate[0].baseRate;

                            if (hotelroomrow.RateInfos.RateInfo[0].ConvertedRateInfo.Surcharges != null)
                            {
                                row["surchargeAmount"] = hotelroomrow.RateInfos.RateInfo[0].ConvertedRateInfo.Surcharges.Surcharge[0].amount;
                                row["surchargeType"] = hotelroomrow.RateInfos.RateInfo[0].ConvertedRateInfo.Surcharges.Surcharge[0].type;
                            }
                        }
                    }
                }

                row["cancellationPolicy"] = hotelroomrow.cancellationPolicy;

                if (hotelroomrow.RoomType != null)
                {
                    row["roomTypeCode"] = hotelroomrow.RoomType.roomCode;
                    row["roomTypeDescription"] = hotelroomrow.RoomType.description;
                    row["roomTypeDescriptionLong"] = hotelroomrow.RoomType.descriptionLong;

                    if (hotelroomrow.RoomType.roomAmenities != null)
                    {
                        int i = 0;
                        foreach (CE.HotelEan.RoomAmenity amenityrow in hotelroomrow.RoomType.roomAmenities.RoomAmenity)
                        {
                            if (i == 0)
                            {
                                row["rooomTypeAmenities"] = amenityrow.amenity;
                            }
                            else
                            {
                                row["rooomTypeAmenities"] = row["rooomTypeAmenities"] + " - " + amenityrow.amenity;
                            }


                            i++;
                        }

                    }
                }
                else
                {
                    if (hotelroomrow.roomTypeDescription != null)
                    {
                        row["roomTypeDescription"] = hotelroomrow.roomTypeDescription;
                    }

                    if (hotelroomrow.rateDescription != null)
                    {
                        row["roomTypeDescriptionLong"] = hotelroomrow.rateDescription;
                    }
                }

            }


            if (hotelroomrow.ValueAdds != null)
            {
                row["valueAdds"] = "";

                foreach (CE.HotelEan.valueAdd vadds in hotelroomrow.ValueAdds.ValueAdd)
                {
                    row["valueAdds"] += vadds.description + ", ";
                }
            }

            row["deepLink"] = hotelroomrow.deepLink;


            row["promoDescription"] = hotelroomrow.promoDescription;

            string arr_nightbaserate = "";
            string arr_nightrate = "";
            string arr_nightsurchargetype = "";
            string arr_nightsurchargeamount = "";
            string arr_promo = "";

            int irow = 0;

            if (hotelroomrow.RateInfos.RateInfo[0].ChargeableRateInfo.NightlyRatesPerRoom != null)
            {
                if (hotelroomrow.RateInfos.RateInfo[0].ChargeableRateInfo.currencyCode == "SGD")
                {
                    foreach (CE.HotelEan.NightlyRate nightrow in hotelroomrow.RateInfos.RateInfo[0].ChargeableRateInfo.NightlyRatesPerRoom.NightlyRate)
                    {
                        if (irow == 0)
                        {
                            arr_nightbaserate = nightrow.baseRate.ToString();
                            arr_nightrate = nightrow.rate.ToString();
                            arr_promo = nightrow.promo.ToString();
                        }
                        else
                        {
                            arr_nightbaserate = arr_nightbaserate + "," + nightrow.baseRate.ToString();
                            arr_nightrate = arr_nightrate + "," + nightrow.rate.ToString();
                            arr_promo = arr_promo + "," + nightrow.promo.ToString();
                        }

                        irow++;
                    }
                }
                else
                {
                    foreach (CE.HotelEan.NightlyRate nightrow in hotelroomrow.RateInfos.RateInfo[0].ConvertedRateInfo.NightlyRatesPerRoom.NightlyRate)
                    {
                        if (irow == 0)
                        {
                            arr_nightbaserate = nightrow.baseRate.ToString();
                            arr_nightrate = nightrow.rate.ToString();
                            arr_promo = nightrow.promo.ToString();
                        }
                        else
                        {
                            arr_nightbaserate = arr_nightbaserate + "," + nightrow.baseRate.ToString();
                            arr_nightrate = arr_nightrate + "," + nightrow.rate.ToString();
                            arr_promo = arr_promo + "," + nightrow.promo.ToString();
                        }

                        irow++;
                    }
                }
            }

            row["ArrayNightlyBaseRate"] = arr_nightbaserate;
            row["ArrayNightlyRate"] = arr_nightrate;
            row["ArrayPromo"] = arr_promo;

            irow = 0;

            if (hotelroomrow.RateInfos.RateInfo[0].ChargeableRateInfo.Surcharges != null)
            {
                if (hotelroomrow.RateInfos.RateInfo[0].ChargeableRateInfo.currencyCode == "SGD")
                {
                    foreach (CE.HotelEan.Surcharge surchargerow in hotelroomrow.RateInfos.RateInfo[0].ChargeableRateInfo.Surcharges.Surcharge)
                    {
                        if (irow == 0)
                        {
                            arr_nightsurchargetype = surchargerow.type.ToString();
                            arr_nightsurchargeamount = surchargerow.amount.ToString();
                        }
                        else
                        {
                            arr_nightsurchargetype = arr_nightsurchargetype + "," + surchargerow.type.ToString();
                            arr_nightsurchargeamount = arr_nightsurchargeamount + "," + surchargerow.amount.ToString();
                        }

                        irow++;
                    }
                }
                else
                {
                    foreach (CE.HotelEan.Surcharge surchargerow in hotelroomrow.RateInfos.RateInfo[0].ConvertedRateInfo.Surcharges.Surcharge)
                    {
                        if (irow == 0)
                        {
                            arr_nightsurchargetype = surchargerow.type.ToString();
                            arr_nightsurchargeamount = surchargerow.amount.ToString();
                        }
                        else
                        {
                            arr_nightsurchargetype = arr_nightsurchargetype + "," + surchargerow.type.ToString();
                            arr_nightsurchargeamount = arr_nightsurchargeamount + "," + surchargerow.amount.ToString();
                        }

                        irow++;
                    }
                }
            }

            row["ArraySurchargeType"] = arr_nightsurchargetype;
            row["ArraySurchargeAmount"] = arr_nightsurchargeamount;

            //GetHotelRateRules/Desc

            if (hotelroomrow.supplierType != CE.HotelEan.SupplierType.E)
            {
                CE.HotelEan.HotelRateRulesResponse hotelrateresp = new CE.HotelEan.HotelRateRulesResponse();
                hotelrateresp = GetRateRules(roomresponse.customerSessionId, hotelroomrow.rateCode, hotelroomrow.roomTypeCode, (HotelWS.SupplierType)hotelroomrow.supplierType, roomresponse.arrivalDate, roomresponse.departureDate);

                if (hotelrateresp != null && hotelrateresp.EanWsError == null)
                {
                    row["rateRules-ratePlanText"] = hotelrateresp.ratePlanText;
                    row["rateRules-nativeCurrencyCode"] = hotelrateresp.nativeCurrencyCode;
                    row["rateRules-guaranteeMethods"] = hotelrateresp.guaranteeMethods;
                    row["rateRules-cancellationPolicy"] = hotelrateresp.cancellationPolicy;
                    row["rateRules-miscellaneous"] = hotelrateresp.miscellaneous;
                    row["rateRules-extraChargeRollawayAdult"] = hotelrateresp.extraChargeRollawayAdult;

                    row["rateRules-extraChargeCrib"] = hotelrateresp.extraChargeCrib;
                    row["rateRules-extraChargeAdult"] = hotelrateresp.extraChargeAdult;
                    row["rateRules-roomDescription"] = hotelrateresp.roomDescription;
                    row["rateRules-roomRate"] = hotelrateresp.roomRate;
                    row["rateRules-totalRoomRate"] = hotelrateresp.totalRoomRate;
                }
                else
                {
                    lblMessage.Text += hotelrateresp.EanWsError.presentationMessage;
                }
            }

            dtRoomTbl.Rows.Add(row);

            gvRooms.DataSource = dtRoomTbl;
            gvRooms.DataBind();
            //HtmlGenericControl divRoomInfo = new HtmlGenericControl("div");

            //divRoomInfo.InnerHtml = "<b>" + hotelroomrow.roomTypeDescription + "</b><br/>";

            //if (hotelroomrow.ValueAdds != null)
            //{
            //    if (hotelroomrow.ValueAdds.size > 0)
            //    {
            //        divRoomInfo.InnerHtml += "includes: ";

            //        for (int i = 0; i < hotelroomrow.ValueAdds.size; i++)
            //        {
            //            if (i == (hotelroomrow.ValueAdds.size - 1))
            //            {
            //                divRoomInfo.InnerHtml += hotelroomrow.ValueAdds.ValueAdd[i].description;
            //            }
            //            else
            //            {
            //                divRoomInfo.InnerHtml += hotelroomrow.ValueAdds.ValueAdd[i].description + ", ";
            //            }
            //        }
            //    }
            //}
            //divRoomInfo.InnerHtml += "<br/>";

            ////divRoomInfo.InnerHtml += hotelroomrow.RoomType.descriptionLong;


            //divRoomInfo.InnerHtml += "<br/>";

            //HtmlGenericControl divRateInfo = new HtmlGenericControl("div");
            //divRateInfo.InnerHtml = "Avg Nightly Rate <br/><b>" + hotelroomrow.RateInfo.ChargeableRateInfo.currencyCode + " " + hotelroomrow.RateInfo.ChargeableRateInfo.averageRate.ToString() + "</b>";

            //Button btnBook = new Button();
            //btnBook.Text = "Book Now!";


            //tdRoomType.Controls.Add(divRoomInfo);
            //tdRoomType.Controls.Add(divRateInfo);
            //tdRoomType.Controls.Add(btnBook);
        }


    }

    protected void gvRooms_RowDatabound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            Label lblRoomType = new Label();
            lblRoomType = (Label)e.Row.FindControl("lblRoomType");
            lblRoomType.Text = DataBinder.Eval(e.Row.DataItem, "roomTypeDescription").ToString();

            Label lblValueAdded = new Label();
            lblValueAdded = (Label)e.Row.FindControl("lblValueAdded");
            string valadded = DataBinder.Eval(e.Row.DataItem, "valueAdds").ToString();

            if (valadded.Length > 1)
            {
                lblValueAdded.Text = "Included: " + valadded.Remove(valadded.Length - 2, 1);
            }

            HyperLink lnkRateDetails = new HyperLink();
            lnkRateDetails = (HyperLink)e.Row.FindControl("lnkRateDetails");

            Label lblDescription = new Label();
            lblDescription = (Label)e.Row.FindControl("lblDescription");

            _suppliertype = DataBinder.Eval(e.Row.DataItem, "Suppliertype").ToString();
            if (_suppliertype == "E")
            {
                lblDescription.Text = DataBinder.Eval(e.Row.DataItem, "roomTypeDescriptionLong").ToString();

                lnkRateDetails.Visible = false;
            }
            else
            {
                //lblDescription.Text = DataBinder.Eval(e.Row.DataItem, "roomTypeDescriptionLong").ToString();
                lblDescription.Text = "Important rate information  <br/>";
                lblDescription.Text += "* Room rate disclaimer: " + DataBinder.Eval(e.Row.DataItem, "roomTypeDescriptionLong").ToString() + "<br/>";
                lblDescription.Text += "* The hotel requires a credit card guarantee for this room. <br/>";
                lblDescription.Text += "* The hotel can only guarantee this rate for 2 or less guests in this room. ";
                lblDescription.Text += "If there are more guests, additional charges may incur, or the property may advise an additional room. <br/>";

                if (DataBinder.Eval(e.Row.DataItem, "taxRate").ToString() != "")
                {
                    lblDescription.Text += "* Note that this property usually charges taxes: " + DataBinder.Eval(e.Row.DataItem, "taxRate").ToString() + "<br/>";
                }

                if (DataBinder.Eval(e.Row.DataItem, "rateInfoRateChange").ToString() == "True")
                {
                    lblDescription.Text += "* Rate changes during the dates requested and the single nightly rate displayed is the highest nightly rate of the dates requested without taxes and fees.";
                }
                //divmoredetails
                HtmlGenericControl divRateDetails = new HtmlGenericControl("div");
                divRateDetails = (HtmlGenericControl)e.Row.FindControl("divRateDetails");

                lnkRateDetails.Attributes.Add("onclick", "showrates('" + divRateDetails.ClientID + "');return false;");
                lnkRateDetails.Attributes.Add("style", "cursor:pointer;");

                lnkRateDetails.Visible = true;

                //RATE DETAILS
                string nativecurrency = DataBinder.Eval(e.Row.DataItem, "rateRules-nativeCurrencyCode").ToString();

                Label lblAgencyHotelName = new Label();
                lblAgencyHotelName = (Label)e.Row.FindControl("lblAgencyHotelName");
                lblAgencyHotelName.Text = lblHotelName.Text;

                Label lblAgencyCheckin = new Label();
                lblAgencyCheckin = (Label)e.Row.FindControl("lblAgencyCheckin");
                lblAgencyCheckin.Text = Convert.ToDateTime(DataBinder.Eval(e.Row.DataItem, "arrivalDate").ToString(), System.Globalization.CultureInfo.InvariantCulture).ToLongDateString();

                Label lblAgencyCheckout = new Label();
                lblAgencyCheckout = (Label)e.Row.FindControl("lblAgencyCheckout");
                lblAgencyCheckout.Text = Convert.ToDateTime(DataBinder.Eval(e.Row.DataItem, "departureDate").ToString(), System.Globalization.CultureInfo.InvariantCulture).ToLongDateString();

                Label lblAgencyRoom = new Label();
                lblAgencyRoom = (Label)e.Row.FindControl("lblAgencyRoom");
                lblAgencyRoom.Text = DataBinder.Eval(e.Row.DataItem, "roomTypeDescriptionLong").ToString();

                Label lblAgencyNightlyRate = new Label();
                lblAgencyNightlyRate = (Label)e.Row.FindControl("lblAgencyNightlyRate");
                lblAgencyNightlyRate.Text = DataBinder.Eval(e.Row.DataItem, "rateRules-roomRate").ToString() + " " + nativecurrency;

                Label lblAgencyTotalRate = new Label();
                lblAgencyTotalRate = (Label)e.Row.FindControl("lblAgencyTotalRate");
                lblAgencyTotalRate.Text = DataBinder.Eval(e.Row.DataItem, "rateRules-totalRoomRate").ToString() + " " + nativecurrency;

                Label lblAgencyRoomType = new Label();
                lblAgencyRoomType = (Label)e.Row.FindControl("lblAgencyRoomType");
                lblAgencyRoomType.Text = DataBinder.Eval(e.Row.DataItem, "rateRules-ratePlanText").ToString();

                Label lblAgencyCurrency = new Label();
                lblAgencyCurrency = (Label)e.Row.FindControl("lblAgencyCurrency");
                lblAgencyCurrency.Text = nativecurrency;

                Label lblAgencyRoomDesc = new Label();
                lblAgencyRoomDesc = (Label)e.Row.FindControl("lblAgencyRoomDesc");
                lblAgencyRoomDesc.Text = DataBinder.Eval(e.Row.DataItem, "rateRules-roomDescription").ToString();


            }

            //divmoredetails
            HtmlGenericControl divmoredetails = new HtmlGenericControl("div");
            divmoredetails = (HtmlGenericControl)e.Row.FindControl("divmoredetails");

            HyperLink lnkMoredetails = new HyperLink();
            lnkMoredetails = (HyperLink)e.Row.FindControl("lnkMoredetails");
            lnkMoredetails.Attributes.Add("onclick", "showmoredetails('" + divmoredetails.ClientID + "');");
            lnkMoredetails.Attributes.Add("style", "cursor:pointer;");

            Label lblRoomAmenities = new Label();
            lblRoomAmenities = (Label)e.Row.FindControl("lblRoomAmenities");
            lblRoomAmenities.Text = DataBinder.Eval(e.Row.DataItem, "rooomTypeAmenities").ToString();

            Label lblCancellation = new Label();
            lblCancellation = (Label)e.Row.FindControl("lblCancellation");
            lblCancellation.Text = DataBinder.Eval(e.Row.DataItem, "cancellationPolicy").ToString();

            Label lblCurrency = new Label();
            lblCurrency = (Label)e.Row.FindControl("lblCurrency");
            lblCurrency.Text = DataBinder.Eval(e.Row.DataItem, "currencyCode").ToString();

            Label lblAveRate = new Label();
            lblAveRate = (Label)e.Row.FindControl("lblAveRate");
            lblAveRate.Text = string.Format("{0:0,0.00}", float.Parse(DataBinder.Eval(e.Row.DataItem, "averageBaseRate").ToString()));

            if (lblAveRate.Text == "00.00" && _suppliertype != "E")
            {
                lblAveRate.Text = string.Format("{0:0,0.00}", float.Parse(DataBinder.Eval(e.Row.DataItem, "maxNightlyRate").ToString()));
            }

            if (DataBinder.Eval(e.Row.DataItem, "promo").ToString() != "" && DataBinder.Eval(e.Row.DataItem, "promo").ToString() == "True")
            {
                lblCurrency.Text = "<s>" + lblCurrency.Text + "</s>";
                lblAveRate.Text = "<s>" + lblAveRate.Text + "</s>";

                Label lblPromoDesc = new Label();
                lblPromoDesc = (Label)e.Row.FindControl("lblPromoDesc");
                lblPromoDesc.Text = "SPECIAL PROMO! " + DataBinder.Eval(e.Row.DataItem, "promoDescription").ToString() + "<br/>";

                Label lblCurrency2 = new Label();
                lblCurrency2 = (Label)e.Row.FindControl("lblCurrency2");
                lblCurrency2.Text = DataBinder.Eval(e.Row.DataItem, "currencyCode").ToString();

                Label lblPromoPrice = new Label();
                lblPromoPrice = (Label)e.Row.FindControl("lblPromoPrice");
                lblPromoPrice.Text = string.Format("{0:0,0.00}", float.Parse(DataBinder.Eval(e.Row.DataItem, "averageRate").ToString()));

            }
            //Button btnBookNow = new Button();
            //btnBookNow = (Button)e.Row.FindControl("btnBookNow");
            //btnBookNow.OnClientClick

            HyperLink hlnkBook = new HyperLink();
            hlnkBook = (HyperLink)e.Row.FindControl("hlnkBook");


            Uri myUri = new Uri(HttpContext.Current.Request.Url.ToString());
            string domainUrl = "http://" + myUri.Host;

            hlnkBook.NavigateUrl = domainUrl + "/travel-hotels/booking/book.aspx?hid=" + DataBinder.Eval(e.Row.DataItem, "hotelid").ToString()
                + "&rcode=" + DataBinder.Eval(e.Row.DataItem, "rateCode").ToString()
                + "&rtype=" + DataBinder.Eval(e.Row.DataItem, "roomTypeCode").ToString()
                + "&rkey=" + DataBinder.Eval(e.Row.DataItem, "rateKey").ToString();

            hlnkBook.NavigateUrl = hlnkBook.ResolveClientUrl(hlnkBook.NavigateUrl).Replace("http", "https");

            Label lblNightlyRate = new Label();
            lblNightlyRate = (Label)e.Row.FindControl("lblNightlyRate");
            //lblNightlyRate.Text = "<b>Sun</b> <br/> $343";
            //lblNightlyRate.Text = DataBinder.Eval(e.Row.DataItem, "ArrayNightlyBaseRate").ToString();


            DateTime dtCheckout = Convert.ToDateTime(DataBinder.Eval(e.Row.DataItem, "departureDate").ToString(), System.Globalization.CultureInfo.InvariantCulture);
            DateTime dtCheckin = Convert.ToDateTime(DataBinder.Eval(e.Row.DataItem, "arrivalDate").ToString(), System.Globalization.CultureInfo.InvariantCulture);
            TimeSpan dateDiffCheck = dtCheckout - dtCheckin;
            int NoOfNights = int.Parse(dateDiffCheck.TotalDays.ToString());

            if (DataBinder.Eval(e.Row.DataItem, "suppliertype").ToString() == "E")
            {
                lblNightlyRate.Text = "<i>nightly rate:</i> <br/>";
                string[] arr_nightbaserate = DataBinder.Eval(e.Row.DataItem, "ArrayNightlyBaseRate").ToString().Split(',');
                string[] arr_nightrate = DataBinder.Eval(e.Row.DataItem, "ArrayNightlyRate").ToString().Split(',');
                string[] arr_promo = DataBinder.Eval(e.Row.DataItem, "ArrayPromo").ToString().Split(',');

                for (int NightNum = 0; NightNum < NoOfNights; NightNum++)
                {
                    DateTime dtHotel = dtCheckin.AddDays(NightNum);
                    string realrate = "";
                    lblNightlyRate.Text += dtHotel.ToString("dd MMM yyyy") + " - " + dtHotel.ToString("ddd");

                    if (arr_nightbaserate.Length > 0)
                    {
                        realrate = " S$" + arr_nightbaserate[NightNum];
                    }

                    if (arr_promo.Length > 0)
                    {
                        if (arr_promo[NightNum].ToString() != "" && arr_promo[NightNum].ToString() == "True")
                        {
                            lblNightlyRate.Text += "<s>" + realrate + "</s> ";
                            lblNightlyRate.Text += "S$" + arr_nightrate[NightNum] + " <br/>";
                            // arr_nightrate
                        }
                        else
                        {
                            lblNightlyRate.Text += realrate + "<br/>";

                        }

                    }


                }

            }
            //string[] arr_nightrate = new string[noOfNights];
            //string[] arr_nightsurchargetype = new string[noOfNights];
            //string[] arr_nightsurchargeamount = new string[noOfNights];
            //string[] arr_promo = new string[noOfNights];
        }
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("results.aspx");
    }
    private string getXMLResult(string requestData)
    {
        WebRequest request = null;
        request = WebRequest.Create(requestData);
        request.Method = "GET";
        WebResponse response = request.GetResponse();
        Stream dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();
        responseFromServer = responseFromServer.Replace("@", "");
        reader.Close();
        dataStream.Close();
        response.Close();

        return responseFromServer;
    }
}
